﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ImportPszxToCurrentStudy.CApImportPszxToCurrentStudyApp
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using EngineeringInternalExtension;
using EngineeringInternalExtension.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Resources;
using System.Windows.Forms;
using Tecnomatix.Engineering;


namespace DnProcessSimulateCommands.ImportPszxToCurrentStudy;

internal class CApImportPszxToCurrentStudyApp
{
  private string m_PszxPath;
  private string m_pszPath;
  private Hashtable m_CojtHashTable;
  private const string MESSAGEBOX_IDENTIFIER = "File exists dialog";

  public CApImportPszxToCurrentStudyApp()
  {
    this.m_CojtHashTable = new Hashtable();
    TxDoNotShowThisMessageAgainMessageBoxEx.CleanRegistry("File exists dialog");
  }

  public string PszxPath
  {
    set => this.m_PszxPath = value;
  }

  public void ImportPszxToCurrentStudy(TxAddToStudyFromFileDataEx pszData)
  {
    string tempPath = Path.GetTempPath();
    string str1 = Path.Combine(tempPath, Path.GetRandomFileName());
    string str2 = Path.Combine(tempPath, Path.GetRandomFileName());
    this.CreateCleanTempDirectories(str1);
    this.CreateCleanTempDirectories(str2);
    this.UnzipPszxToTempDirectories(str1, str2);
    if (!this.IsStudyCompatible(this.m_pszPath))
      return;
    string systemRootDirectory = TxApplication.SystemRootDirectory;
    this.CopyLibraryFiles(str2, systemRootDirectory);
    if (!this.AddPszToStudy(this.m_pszPath, pszData))
      TxErrorStack.Push("FAILED_TO_IMPORT_PSZX_FILE", new ArrayList()
      {
        (object) this.m_PszxPath,
        (object) this.GetResourceManager().GetString("IMPORT_PSZX_DLG_IMPORT_FAILED_MSG")
      });
    this.DeleteTempDirectory(str1);
    this.DeleteTempDirectory(str2);
  }

  private void UnzipPszxToTempDirectories(string tempDirectoryPszx, string tempDirectoryLibrary)
  {
    this.UnzipPszx(tempDirectoryPszx);
    this.SetAndCheckPszName(tempDirectoryPszx);
    this.UnZipLibrary(tempDirectoryPszx, tempDirectoryLibrary);
  }

  private void UnZipLibrary(string tempDirectoryPszx, string tempDirectoryLibrary)
  {
    string[] files = Directory.GetFiles(tempDirectoryPszx, "Library.zip", SearchOption.TopDirectoryOnly);
    if (((IEnumerable<string>) files).Count<string>() < 1)
    {
      Directory.Delete(tempDirectoryPszx, true);
      throw new Exception(this.GetResourceManager().GetString("IMPORT_PSZX_DLG_MISSING_ZIP_LIBRARY_ERROR"));
    }
    TxZipUtilitiesEx.UnzipFiles(files[0], tempDirectoryLibrary);
  }

  private void SetAndCheckPszName(string tempDirectoryPszx)
  {
    string withoutExtension = Path.GetFileNameWithoutExtension(this.m_PszxPath);
    string[] files = Directory.GetFiles(tempDirectoryPszx, withoutExtension + ".psz", SearchOption.TopDirectoryOnly);
    if (((IEnumerable<string>) files).Count<string>() < 1)
    {
      Directory.Delete(tempDirectoryPszx, true);
      throw new Exception(this.GetResourceManager().GetString("IMPORT_PSZX_DLG_MISSING_PSZ_ERROR"));
    }
    this.m_pszPath = files[0];
  }

  private void CreateCleanTempDirectories(string directoryName)
  {
    if (Directory.Exists(directoryName))
      Directory.Delete(directoryName, true);
    else
      Directory.CreateDirectory(directoryName);
  }

  private void DeleteTempDirectory(string directoryName)
  {
    try
    {
      Directory.Delete(directoryName, true);
    }
    catch (Exception ex)
    {
      TxErrorStack.PushWarning("FAILED_TO_DELETE_TEMP_DIRECTORY", directoryName);
    }
  }

  private bool AddPszToStudy(string pszFilePath, TxAddToStudyFromFileDataEx pszData)
  {
    TxDocumentEx txDocumentEx = new TxDocumentEx();
    pszData.SourceFilePath = pszFilePath;
    pszData.SourceFileFormat = (TxFileFormatEx) 0;
    return txDocumentEx.AddToStudyFromFile(pszData);
  }

  private bool IsStudyCompatible(string pszFilePath)
  {
    return this.AddPszToStudy(pszFilePath, new TxAddToStudyFromFileDataEx()
    {
      AddMfgs = false,
      AddEngData = false,
      AddResources = false,
      AddParts = false
    });
  }

  private void UnzipPszx(string destinationDirectory)
  {
    string str = destinationDirectory + "\\\\temp.pszx";
    File.Copy(this.m_PszxPath, str);
    TxZipUtilitiesEx.UnzipFiles(str, destinationDirectory);
    File.Delete(str);
  }

  private void CopyLibraryFiles(string sourceDirectory, string destinationDirectory)
  {
    Dictionary<string, bool> table = this.InsertFilesInDirectoryToTable(sourceDirectory);
    foreach (string str in table.Keys.ToList<string>())
    {
      if (!table[str])
      {
        if (this.IsFileInCoOrCojtFolder(str))
          this.HandleCojtFile(str, sourceDirectory, destinationDirectory, table);
        else
          this.HandleFile(str, sourceDirectory, destinationDirectory, table);
      }
    }
  }

  private Dictionary<string, bool> InsertFilesInDirectoryToTable(string directoryPath)
  {
    string[] files = Directory.GetFiles(directoryPath, "*.*", SearchOption.AllDirectories);
    Dictionary<string, bool> table = new Dictionary<string, bool>();
    foreach (string key in files)
      table.Add(key, false);
    return table;
  }

  private bool IsFileInCoOrCojtFolder(string filePath)
  {
    return filePath.Contains(".co\\") || filePath.Contains(".cojt\\");
  }

  private void HandleFile(
    string filePath,
    string soureDirectory,
    string destinationDirectory,
    Dictionary<string, bool> fileAndHandeledStatus)
  {
    bool flag = true;
    string str1 = filePath.Substring(soureDirectory.Length + 1);
    string str2 = destinationDirectory + str1;
    if (File.Exists(str2))
      flag = this.ShowFileAlreadyExistsDlg(str2).Equals((object) DialogResult.Yes);
    if (flag)
      this.CopyFile(filePath, soureDirectory, destinationDirectory);
    fileAndHandeledStatus[filePath] = true;
  }

  private string GetCoOrCojtDirectoryName(string fileFullName)
  {
    int num1 = fileFullName.IndexOf(".cojt");
    if (num1 != -1)
      return fileFullName.Substring(0, num1 + 5);
    int num2 = fileFullName.IndexOf(".co");
    return fileFullName.Substring(0, num2 + 3);
  }

  private void HandleCojtFile(
    string sourceFileFullName,
    string sourceDirectory,
    string destinationDirectory,
    Dictionary<string, bool> fileAndHandeledStatus)
  {
    string str1 = sourceFileFullName.Substring(sourceDirectory.Length + 1);
    string cojtDirectoryName1 = this.GetCoOrCojtDirectoryName(destinationDirectory + str1);
    string cojtDirectoryName2 = this.GetCoOrCojtDirectoryName(sourceFileFullName);
    bool flag = true;
    if (Directory.Exists(cojtDirectoryName1))
      flag = this.ShowFileAlreadyExistsDlg(cojtDirectoryName1).Equals((object) DialogResult.Yes);
    foreach (string str2 in fileAndHandeledStatus.Keys.ToList<string>())
    {
      if (str2.Contains(cojtDirectoryName2))
      {
        if (flag)
          this.CopyFile(str2, sourceDirectory, destinationDirectory);
        fileAndHandeledStatus[str2] = true;
      }
    }
  }

  private DialogResult ShowFileAlreadyExistsDlg(string filePath)
  {
    return TxDoNotShowAgainMessageBox.Show($"{this.GetResourceManager().GetString("IMPORT_PSZX_DLG_ERROR_MESSAGE_PART1")} {filePath} {this.GetResourceManager().GetString("IMPORT_PSZX_DLG_ERROR_MESSAGE_PART2")}", this.GetResourceManager().GetString("IMPORT_PSZX_DLG_ERROR_MESSAGE_CAPTION"), "File exists dialog", MessageBoxButtons.YesNo);
  }

  private DialogResult ShowCopyFailedDlg(string filePath)
  {
    return TxDoNotShowAgainMessageBox.Show($"{this.GetResourceManager().GetString("IMPORT_PSZX_DLG_COPY_FAILED_ERROR_PART1")} {filePath}.{Environment.NewLine}{this.GetResourceManager().GetString("IMPORT_PSZX_DLG_COPY_FAILED_ERROR_PART2")}", this.GetResourceManager().GetString("IMPORT_PSZX_DLG_ERROR_MESSAGE_CAPTION"), "File exists dialog", MessageBoxButtons.AbortRetryIgnore, DialogResult.Ignore);
  }

  private bool DoesFileAlreadyExistsInDestinationDirectory(
    string fileName,
    string destinationDirectory)
  {
    return ((IEnumerable<string>) Directory.GetFiles(destinationDirectory, fileName, SearchOption.TopDirectoryOnly)).Count<string>() > 0;
  }

  private void SetHiddenFlag(bool shouldSet, FileInfo fileInfo)
  {
    if (!(fileInfo.Exists & shouldSet))
      return;
    fileInfo.Attributes |= FileAttributes.Hidden;
  }

  private void RemoveHiddenFlag(bool shouldSet, FileInfo fileInfo)
  {
    if (!(fileInfo.Exists & shouldSet))
      return;
    fileInfo.Attributes &= ~FileAttributes.Hidden;
  }

  private void CopyFileEvenIfHidden(string sourceFileName, string targetFilename)
  {
    if (sourceFileName.ToLower().Contains("thumbs.db"))
      return;
    FileInfo fileInfo = new FileInfo(targetFilename);
    bool shouldSet = fileInfo.Exists && fileInfo.Attributes.HasFlag((Enum) FileAttributes.Hidden);
    try
    {
      this.RemoveHiddenFlag(shouldSet, fileInfo);
      File.Copy(sourceFileName, targetFilename, true);
    }
    catch (Exception ex)
    {
      this.SetHiddenFlag(shouldSet, fileInfo);
      throw;
    }
  }

  private void CopyFile(string sourceFileName, string sourceDirectory, string destinationDirectory)
  {
    string str1 = sourceFileName.Substring(sourceDirectory.Length + 1);
    string str2 = !destinationDirectory.EndsWith("\\") ? $"{destinationDirectory}\\{str1}" : destinationDirectory + str1;
    string path = str2.Replace(Path.GetFileName(str2), "");
    try
    {
      if (!Directory.Exists(path))
        Directory.CreateDirectory(path);
      this.CopyFileEvenIfHidden(sourceFileName, str2);
    }
    catch (Exception ex)
    {
      switch (this.ShowCopyFailedDlg(str2))
      {
        case DialogResult.Abort:
          this.PushCopyWarningOnErrorStack(str2);
          throw new UserAbortException();
        case DialogResult.Retry:
          this.CopyFile(sourceFileName, sourceDirectory, destinationDirectory);
          break;
        default:
          this.PushCopyWarningOnErrorStack(str2);
          break;
      }
    }
  }

  private string CreateOverwriteMessage(string filePath)
  {
    return $"{this.GetResourceManager().GetString("FILE_EXISTS_ERROR_MESSAGE_PART1")} {filePath} {this.GetResourceManager().GetString("FILE_EXISTS_ERROR_MESSAGE_PART2")}";
  }

  public void PushImportErrorOnErrorStack(string error)
  {
    TxErrorStack.Push("FAILED_TO_IMPORT_PSZX_FILE", new ArrayList()
    {
      (object) this.m_PszxPath,
      (object) error
    });
  }

  public void PushCopyWarningOnErrorStack(string error)
  {
    TxErrorStack.PushWarning("FAILED_TO_COPY_FILE", error);
  }

  private ResourceManager GetResourceManager()
  {
    return new ResourceManager("DnProcessSimulateCommands.ImportPszxToCurrentStudy.Resources.StringTable", this.GetType().Assembly);
  }
}
